package com.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;

import com.sky.exception.LoginFailedException;


import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.utils.HttpClientUtil;
import com.user.mapper.UserMapper;
import com.user.pojo.dto.UserLoginDTO;
import com.user.pojo.entity.User;
import com.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatProperties weChatProperties;
    /**
     * 微信登陆
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
           //将获取openId的过程封装成一个对象
           String openid=getOpenid(userLoginDTO.getCode());
           //判断是否为空
           if(openid==null){
               throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
           }
           //判断用户是否已经登录过
           User user=userMapper.getUserByOpenid(openid);
           //如果是新用户自动完成注册
           if(user==null){
              user=User.builder().openid(openid)
                      .createTime(LocalDateTime.now())
                      .build();
              userMapper.insert(user);
           }
           //返回查询的对象
           return user;
    }

    /**
     * 根据map统计用户数量
     * @param map
     * @return
     */
    @Override
    public Result<Integer> countUserByMap(Map<String, Object> map) {
        Integer userSum = userMapper.countUserByMap(map);
        if(userSum==null){return Result.error("未知错误");}
        return Result.success(userSum);
    }

    private String getOpenid(String code){
        //调用微信服务接口，获取openid httpclient
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);//获得json
        //json串转为JsonObject对象
        JSONObject jsonObject= JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
